{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module FunBot.Settings.Persist
    ( loadBotSettings
    , mkSaveBotSettings
    , saveBotSettings
    )
where

import Control.Monad.IO.Class (liftIO)
import Data.JsonState
import Data.Settings.Types (getSettings)
import Data.Time.Units
import FunBot.Config (settingsFilename, stateSaveInterval)
import FunBot.Settings.Instances
import FunBot.Types
import Network.IRC.Fun.Bot.State (askEnvS)
import Network.IRC.Fun.Bot.Types

saveInterval = 3 :: Second

loadBotSettings :: Config -> IO Settings
loadBotSettings cfg = do
    r <- loadState $
         stateFilePath settingsFilename (cfgStateRepo cfg)
    case r of
        Left (False, e) -> error $ "Failed to read settings file: " ++ e
        Left (True, e)  -> error $ "Failed to parse settings file: " ++ e
        Right s         -> return s

mkSaveBotSettings :: Config -> IO (Settings -> IO ())
mkSaveBotSettings cfg =
    mkSaveStateChoose
        stateSaveInterval
        settingsFilename
        (cfgStateRepo cfg)
        "auto commit by funbot"

saveBotSettings :: BotSession ()
saveBotSettings = do
    sets <- getSettings
    save <- askEnvS saveSettings
    liftIO $ save sets
